import java.util.Arrays;
class Solution {
    private List<List<Integer>> ans = new ArrayList<>();
    private List<Integer> arr = new ArrayList<>();
    private boolean[] used;
    private int[] nums;

    public List<List<Integer>> permuteUnique(int[] nums) {
        this.nums = nums;
        Arrays.sort(this.nums);
        this.used = new boolean[this.nums.length];
        find(0);
        return this.ans;
    }
    private void find(int index) {
        if (index == this.nums.length) {
            this.ans.add(new ArrayList<>(arr));
            return;
        }
        for (int i = 0; i < this.nums.length; i++) {
            if(!used[i]) {
                if (i > 0 && this.nums[i] == this.nums[i - 1] && !this.used[i - 1]) continue;
                used[i] = true;
                arr.add(this.nums[i]);
                find(index + 1);
                arr.remove(arr.size() - 1);
                used[i] = false;
            }
        }
    }
}
